/**
 * 取得url参数
 */
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); // 构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  // 匹配目标参数
    if (r != null) return unescape(r[2]);
    return null; // 返回参数值
}
//运费模板查看详情
function info(templateId){
    this.getInfo(templateId,false);
    layer.open({
        type: 1,
        skin: 'layui-layer-molv',
        title: "运费模板详细",
        area: ['900px', '400px'],
        shadeClose: false,
        content: jQuery("#freightLayer"),
        btn: [],
    });
}
var freightVue = new Vue({
    el:'#rrapp',
    data:{
        showList: true,
        title: null,
        freightTemplateList:[],
        freightTemplate: {},
        freightAreaList:[],
        freightAreaList2:[],
        allRegions:[],
        mark: '',
        sum : "",
        sum2 : "",
        q:{
            templateName: ''
        },
        freightDialog:false,
        page: {
            current: 1, // 当前页
            size: 10, // 分页数
            total: 0, // 总条数
        },
    },
    mounted:function(){
        this.freightTemplateSearch();
    },
    methods: {
        query: function () {
            this.reload();
        },
        add: function(){
            this.showList = false;
            this.title = "新增";
            this.freightTemplate = {'freeShipping':'0','valuationWay':'unit','disabled':'0','defTemplate':'0','templateType':'sku','providerType':'shop'};
            this.freightAreaList = [];
            this.freightAreaList2 = [];
        },

        //添加城市
        addCity: function(){
            this.freightAreaList.push({'areaNames':'','areaIds':'','rule':'valuationWay'});
            console.info(this.freightAreaList)
        },
        showCity: function(index){
            this.freightDialog = true;
            this.mark = 'valuationWay';
            this.sum = index;
        },
        delCity: function(index){
            this.freightAreaList.splice(index,1);
        },
        //设置免邮地区
        addFreeArea: function(){
            this.freightAreaList2.push({'areaNames':'','areaIds':'','rule':'freeShipping','firstPrice':'0','continueUnit':'0','continuePrice':'0'});
            console.info(this.freightAreaList2)
        },
        showFreeArea: function(index){
            this.freightDialog = true;
            this.mark = 'freeShipping';
            this.sum = index;
        },
        delFreeArea: function(index){
            this.freightAreaList2.splice(index,1);
        },
        update: function (templateId) {
            this.showList = false;
            this.title = "修改";
            this.getInfo(templateId,true)
        },
        saveOrUpdate: function (event) {
            this.freightTemplate.freightAreaList = this.freightAreaList;
            this.freightTemplate.freightAreaList = this.freightTemplate.freightAreaList.concat(this.freightAreaList2)
            if(this.validator()){
                return ;
            }
            var url = this.freightTemplate.templateId == null ? "freightages/freighttemplate/save" : "freightages/freighttemplate/update";
            var self = this;
            $.ajax({
            	type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data:JSON.stringify(self.freightTemplate),
                success: function(r){
                	if(r.code === 0){
            			alert('操作成功', function(index){
                            self.reload();
            			});
            		}else{
            			alert(r.msg);
            		}
            	}
            });
        },
        del: function (templateId) {
            var nos=[];
            nos.push(templateId)
            var self= this;
            this.$confirm('确定要删除选中的记录？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(function(){
                $.ajax({
                    type: "POST",
                    url: baseURL + "freightages/freighttemplate/delete",
                    contentType: "application/json",
                    data: JSON.stringify(nos),
                    success: function(r){
                        debugger;
                        if(r.code == 0){
                            self.freightTemplateSearch();
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            }).catch(function(){
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        getInfo: function(templateId,boolean){
            var self = this;
            $.get(baseURL + "freightages/freighttemplate/info/"+templateId, function(r){
                self.freightTemplate = r.freightTemplate;
                self.freightAreaList =  r.freightAreaList;
                //取出免邮集合
                if(boolean){
                    if(self.freightAreaList != null && self.freightAreaList.length > 0){
                        for(var i = 0;i<self.freightAreaList.length;i++){
                            if(self.freightAreaList[i].rule == 'freeShipping'){
                                self.freightAreaList2.push(self.freightAreaList[i]);
                                self.freightAreaList.splice(i,1);
                                i--;
                            }
                        }
                    }
                }
            });
        },
        reset: function () {
            this.q.templateName = '';
        },
        reload: function (event) {
            this.showList = true;
            this.freightTemplate = {};
            this.freightAreaList = [];
            this.freightAreaList2 = [];
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                page:page,
                postData:{
                    'templateName': this.q.templateName,
                }
            }).trigger("reloadGrid");
        },
        validator: function () {
            console.log(this.freightTemplate);
            // console.log(this.freightAreaList);
            // console.log(this.freightAreaList2);
            if(isBlank(this.freightTemplate.templateName)){
                alert("运费模板名不能为空!");
                return true;
            }
            //运费模板数字校验
            var check = /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/;
            if(!(check.test(this.freightTemplate.firstUnit)&&check.test(this.freightTemplate.firstPrice)&&check.test(this.freightTemplate.continueUnit)&&check.test(this.freightTemplate.continuePrice))){
                alert("模板参数只能是正数!")
                return true;
            }
            //校验子表数据
            var freightAreaList = this.freightTemplate.freightAreaList;
            for(var i = 0;i<freightAreaList.length;i++){
                if(!(check.test(freightAreaList[i].firstUnit)&&check.test(freightAreaList[i].firstPrice)&&check.test(freightAreaList[i].continueUnit)&&check.test(freightAreaList[i].continuePrice))){
                    alert("模板参数只能是正数!")
                    return true;
                }
                if(isBlank(freightAreaList[i].areaNames)){
                    alert("地区不能为空!")
                    return true;
                }
            }
        },
        handleClose:function(){

        },
        handleNodeClick:function(){


        },
        enterCityChoice:function(){
            var checkedNodes = this.$refs.regionRef.getCheckedNodes();
            var ids = [];
            var names = []
            for (var checkedNode of checkedNodes) {
                ids.push(checkedNode.value);
                names.push(checkedNode.label);
            }
            if(this.mark == 'valuationWay'){
                this.freightAreaList[this.sum].rule = 'valuationWay'
                this.freightAreaList[this.sum].areaNames = names.join(",")
                this.freightAreaList[this.sum].areaIds = ids.join(",")
            }else{
                this.freightAreaList[this.sum].rule = 'freeShipping'
                this.freightAreaList2[this.sum].areaNames = names.join(",")
                this.freightAreaList2[this.sum].areaIds = ids.join(",")
            }
            this.freightDialog = false;
        },
        handleSizeChange: function (val) {
            this.page.size = val;
            this.freightTemplateSearch();
        },

        handleCurrentChange: function (val) {
            this.page.current = val;
            this.freightTemplateSearch();
        },
        freightTemplateSearch:function(){
            var paramData = {};
            paramData.marketable = this.q.marketable;
            paramData.current = this.page.current;
            paramData.size = this.page.size;
            paramData.total = this.page.total;
            var self = this;
            $.ajax({
                type: "POST",
                url: baseURL + "freightages/freighttemplate/newList",
                contentType: "application/json",
                data: JSON.stringify(paramData),
                success: function (r) {
                    if (r.code == 0) {
                        self.page.current = r.page.current;
                        self.page.size = r.page.size;
                        self.page.total = r.page.total;
                        self.freightTemplateList = r.page.records;
                        self.allRegions = r.allRegions;
                    } else {
                        alert(r.msg);
                    }
                }
            })
        }
    }
});